package heima_bixiangdong.pro_con;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 多生产多消费，JDK1.5的Lock和Condition写法
class Resource3{
    private String name;
    private int num=1;
    private boolean flag;
    final private Lock lock = new ReentrantLock();
    final private Condition producer = lock.newCondition();
    final private Condition consumer = lock.newCondition();
    public void set(String name){
        lock.lock();
        try{
            while (flag){
                try {
                    producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.name = name+num;
            System.out.println(Thread.currentThread().getName()+"......................生产者..."+this.name);
            num++;
            flag = true;
            consumer.signal();
        }finally {
            lock.unlock();
        }

    }
    public void out(){
        lock.lock();
        try{
            while (!flag){
                try {
                    consumer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"....消费者...."+this.name);
            flag = false;
            producer.signal();
        }finally {
            lock.unlock();
        }
    }
}

public class LockDemo {
    public static void main(String[] args) {
        test1();
    }

    private static void test1() {
        Resource3 resource3 = new Resource3();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource3.set("面包");
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource3.set("面包");
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource3.out();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource3.out();
                }
            }
        }).start();
    }
}
